from odoo import models, _
from odoo.exceptions import UserError
import requests


class MesLogin(models.AbstractModel):
    _name = 's.mes.login'

    def get_mes_token(self):
        username = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.username')]).s_value
        password = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.password')]).s_value
        login_url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.login')]).s_value
        url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')]).s_value
        if not url:
            url = 'http://10.150.200.14:8888/ims-integrate/console/login'
        if not username or not password:
            self.env['api.records'].create({
                'doc_type': "login",
                'api_route': url,
                'api_params': '请先配置在: s.api.config_parameter表中配置等了mes参数',
                'result_json': '',
                'state': 'fail'
            })
            return
        header = {
            'Content-Type': 'application/json',
        }
        data = {
            "userCode": username,
            "pass": password,
            "language": "zh_CN"
        }
        try:
            res = requests.post(login_url, json=data, headers=header)
        except Exception as e:
            self.env['api.records'].create({
                'doc_type': "login",
                'api_route': url,
                'api_params': '网络请求失败',
                'result_json': '',
                'state': 'fail'
            })
            return
        login_result = res.json()
        if login_result.get('resultCode') != '0000':
            self.env['api.records'].create({
                'doc_type': "login",
                'api_route': url,
                'api_params': '登录失败',
                'result_json': '',
                'state': 'fail'
            })
            return
        result_data = login_result.get('resultData')
        token = result_data.get('accessToken')
        return token

    def get_mes_url(self):
        """url"""
        url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')]).s_value
        return url

    def get_mes_doctype(self, param=None):
        """mes方法名"""
        if not param:
            return None
        else:
            mes_ = self.env['s.api.config_parameter'].search([('s_key', '=', param)])
            return mes_[0].s_value if mes_ else None

    def get_mes_enabled(self, param=None):
        """控制接口是否开启"""
        if not param:
            return None
        else:
            mes_ = self.env['s.api.config_parameter'].search([('s_key', '=', param)])
            return mes_[0].s_value if mes_ else None

